package cn.safekeeper.guide.admin.controller;

import cn.safekeeper.core.SafeKeeper;
import cn.safekeeper.guide.admin.config.WebConfig;
import cn.safekeeper.guide.admin.constant.MsgObj;
import cn.safekeeper.guide.admin.constant.UserConstants;
import cn.safekeeper.guide.admin.domain.entity.SysUser;
import cn.safekeeper.guide.admin.domain.vo.UserVO;
import cn.safekeeper.guide.admin.service.ISysUserService;
import cn.safekeeper.guide.admin.utils.StringUtils;
import cn.safekeeper.guide.admin.utils.file.FileUploadUtils;
import cn.safekeeper.guide.admin.utils.sign.Md5Utils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 首页
 */
@RestController
public class IndexController extends BaseController {
    /**
     * 系统基础配置
     */
    @Autowired
    private WebConfig webConfig;

    /**
     * 访问首页，提示语
     */
    @RequestMapping("/")
    public String index() {
        return StringUtils.format("欢迎使用{}后台管理框架，当前版本：v{}，请通过前端地址访问。", webConfig.getName(), webConfig.getVersion());
    }

    @Autowired
    private ISysUserService userService;

    /**
     * 个人信息
     */
    @GetMapping("/profile/getProfile")
    public MsgObj profile() {
        SysUser user = getLoginUser();
        MsgObj ajax = MsgObj.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(user.getUserName()));
        ajax.put("postGroup", userService.selectUserPostGroup(user.getUserName()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @PostMapping("/profile/updateProfile")
    public MsgObj updateProfile(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return MsgObj.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return MsgObj.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        SysUser sysUserCache = getLoginUser();
        user.setUserId(sysUserCache.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            sysUserCache.setNickName(user.getNickName());
            sysUserCache.setPhonenumber(user.getPhonenumber());
            sysUserCache.setEmail(user.getEmail());
            sysUserCache.setSex(user.getSex());
            SafeKeeper.safeDefault().setSubject(sysUserCache.getUserId(), JSON.toJSONString(sysUserCache));
            return MsgObj.success();
        }
        return MsgObj.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 修改密码
     */
    @PostMapping("/profile/updatePwd")
    public MsgObj updatePwd(@Validated @RequestBody UserVO userVO) {
        SysUser sysUserCache = getLoginUser();

        String oldPassword = Md5Utils.hash(userVO.getOldPassword());
        String newPassword = Md5Utils.hash(userVO.getNewPassword());
        if (!sysUserCache.getPassword().equals(oldPassword)) {
            return error("修改密码失败，旧密码错误");
        }
        if (sysUserCache.getPassword().equals(newPassword)) {
            return error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(sysUserCache.getUserId(), newPassword) > 0) {
            // 更新缓存用户密码
            sysUserCache.setPassword(newPassword);
            SafeKeeper.safeDefault().setSubject(sysUserCache.getUserId(), JSON.toJSONString(sysUserCache));
            return success();
        }
        return MsgObj.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/profile/avatar")
    public MsgObj avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            SysUser sysUserCache = getLoginUser();
            String avatar = FileUploadUtils.upload(WebConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(sysUserCache.getUserId(), avatar)) {
                MsgObj ajax = MsgObj.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                sysUserCache.setAvatar(avatar);
                SafeKeeper.safeDefault().setSubject(sysUserCache.getUserId(), JSON.toJSONString(sysUserCache));
                return ajax;
            }
        }
        return MsgObj.error("上传图片异常，请联系管理员");
    }
}
